<template>
  <div class="text-center">
    <n-space vertical>
      <n-button quaternary @click="handleDownloadQRCode"> 下载 </n-button>
      <n-qr-code
        id="qr-code"
        :size="200"
        :value="text"
        color="#409eff"
        background-color="#F5F5F5"
      />
    </n-space>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref } from 'vue';

  export default defineComponent({
    setup() {
      const text = ref('二维码测试');
      const handleDownloadQRCode = () => {
        const canvas = document
          .querySelector('#qr-code')
          ?.querySelector<HTMLCanvasElement>('canvas');
        if (canvas) {
          const url = canvas.toDataURL();
          const a = document.createElement('a');
          a.download = 'QRCode.png';
          a.href = url;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      }
      return {
        handleDownloadQRCode,
        text,
      };
    },
  });
</script>
